import { CustomTheme, useCustomTheme } from '@/context/ThemeContext';
import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { ArrowLeft } from '@taroify/icons';
import { useState } from 'react';
import { Swiper } from '@taroify/core';
import Tabs from '@/components/menu/Tabs';
import { getCapsuleWidth, getPaddingTop } from '@/utils/back';

interface NavBarProps {
  height?: string;
  left?: React.ReactNode;
  right?: React.ReactNode;
  title?: string | React.ReactNode;
  children?: React.ReactNode;
  align?: 'center' | 'start' | 'end';
  spread?: boolean;
  menu?: string[];
  changeMenu?: (menu: number) => void;
  defaultMenu?: number;
}

function NavBar({
  height = '40px',
  left,
  title,
  children,
  align = 'center',
  spread = true,
  right,
  menu,
  changeMenu,
  defaultMenu = 0,
}: NavBarProps) {
  const { theme } = useCustomTheme();
  const paddingTop = getPaddingTop();
  const width = getCapsuleWidth();
  const [index, setIndex] = useState(defaultMenu);
  function change(i: number) {
    setIndex(i);
    if (changeMenu) changeMenu(i);
  }
  return (
    <View
      style={{
        paddingTop,
        backgroundColor: theme.baseColor,
      }}
      className="min-h-screen box-border"
    >
      <View className={`flex items-${align} mx-2`} style={{ height }}>
        {/* 这里左边空余 */}
        {spread && (
          <View className="min-w-16">
            {left ? (
              <View>{left}</View>
            ) : (
              <ArrowLeft onClick={() => Taro.navigateBack()} size={24} />
            )}
          </View>
        )}

        <View className="flex-grow flex justify-around items-center">
          {title ? title : <Tabs select={index} menus={menu} change={change} />}
        </View>
        <View style={{ width }} className="flex justify-end">
          {right}
        </View>
      </View>
      <Swiper
        value={index}
        style={{
          height: `calc(100vh - ${height} - ${paddingTop}px)`,
        }}
        className=" w-full"
        onChange={change}
        loop={false}
        lazyRender
        stopPropagation={false}
      >
        {title ? (
          <Swiper.Item className="overflow-y-auto">{children}</Swiper.Item>
        ) : (
          menu &&
          menu.map((_, i) => (
            <Swiper.Item className="overflow-y-auto" key={i}>
              {children}
            </Swiper.Item>
          ))
        )}
      </Swiper>
    </View>
  );
}

export default (a: NavBarProps) => (
  <CustomTheme>
    <NavBar {...a}></NavBar>
  </CustomTheme>
);
